//
//  LYlabelViewController.m
//  音伴尔家听宝
//
//  Created by Burgess on 2017/6/12.
//  Copyright © 2017年 Burgess. All rights reserved.
//

#import "LYlabelViewController.h"
#import "JCTagListView.h"
#import "JCTableViewCell.h"
#import "JCCollectionViewTagFlowLayout.h"
#import "LYlabelModel.h"
#import "LYlabelListModel.h"

#import <AFNetworking.h>
#import <MJExtension.h>
#import <UIImage+AFNetworking.h>
#import <UIImageView+AFNetworking.h>

@interface LYlabelViewController () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, weak) IBOutlet JCTagListView *tagListView;

//
@property (nonatomic, strong) NSArray <LYlabelModel *>*labelModel;
@property (nonatomic, strong) NSArray <LYlabelListModel *> *ownLabel;

@property (nonatomic, copy) NSMutableArray<NSMutableArray *> *tableTags;
@property (nonatomic, copy) NSMutableArray *headViewTags;
@property (nonatomic, strong) NSMutableArray *cellHeights;

@property (nonatomic, strong) JCCollectionViewTagFlowLayout *layout;
@property (nonatomic, weak) IBOutlet UITableView *tableView;

@end

@implementation LYlabelViewController

-(void)GetDidSelectLabelModel{
    
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFHTTPSessionManager * manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:config];
    
    NSString *path = [YbrSandBox dicAppendFilePath:initfilename];
    NSDictionary *dicc = [NSDictionary dictionaryWithContentsOfFile:path];
    NSString *str =  dicc[@"userid"];
    NSDictionary * paramDic = @{@"userid" : str};
    
    [manager GET:@"http://cute.fcloudclass.com/api.php/User/get_user_no_label" parameters:paramDic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        self.labelModel = [LYlabelModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"label"]];

        NSMutableArray *Marr1 = [[NSMutableArray alloc]init];
        NSMutableArray *Marr2 = [[NSMutableArray alloc]init];
        NSMutableArray *Marr3 = [[NSMutableArray alloc]init];
        
        self.tableTags = @[Marr1,Marr2,Marr3];
        
        for (int j = 0; j<self.labelModel.count; j++) {
            for (int i = 0; i<self.labelModel[j].label_list.count; i++) {
                NSDictionary *dic  = self.labelModel[j].label_list[i];
                [self.tableTags[j] addObject:dic[@"label_name"]];
            }
        }
        
        for (NSArray *tags in self.tableTags) {
            [self.cellHeights addObject:@([self.layout calculateContentHeight:tags])];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
    
}
-(void)getLabelData{
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFHTTPSessionManager * manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:config];
    NSString *path = [YbrSandBox dicAppendFilePath:initfilename];
    NSDictionary *dicc = [NSDictionary dictionaryWithContentsOfFile:path];
    NSString *str =  dicc[@"userid"];
    NSDictionary * paramDic = @{@"userid" : str};
    
    [manager GET:@"http://cute.fcloudclass.com/api.php/User/get_user_label" parameters:paramDic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        self.ownLabel = [LYlabelListModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"user_label"]];
        
        NSMutableArray *Marr = [[NSMutableArray alloc]init];
        for (int i= 0; i<self.ownLabel.count; i++) {
            [Marr addObject:self.ownLabel[i].label_name];
            
        }
        self.headViewTags = Marr;
    
//        self.tagListView.canSelectTags = YES;
        self.tagListView.tagSelectedTextColor = [UIColor blackColor];
        self.tagListView.tagCornerRadius = 5.0f;
        
//        [self.tagListView.tags addObjectsFromArray:self.headViewTags];
//        
//        [self.tagListView setCompletionBlockWithSelected:^(NSInteger index) {
//           [self performSelector:@selector(delete)];
//        }];
        [self.tagListView.collectionView reloadData];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}

//      选择标签时发送post请求给服务器
-(void)addLabelPostActionWithLabelid:(NSString *)labelid labelName:(NSString *)name{
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFHTTPSessionManager * manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:config];
    NSString *path = [YbrSandBox dicAppendFilePath:initfilename];
    NSDictionary *dicc = [NSDictionary dictionaryWithContentsOfFile:path];
    NSString *str =  dicc[@"userid"];
    NSDictionary * paramDic = @{
                                @"userid" : str,
                                @"labelid":labelid,
                                @"labelname":name
                                };
    
    [manager POST:@"http://cute.fcloudclass.com/api.php/User/set_user_label" parameters:paramDic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"通知服务器 ------ %@ ----   通知服务器",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    //  获取网络数据
    [self GetDidSelectLabelModel];
    [self getLabelData];
    
    //  tableView的相关设置
    self.tableView.delegate            = self;
    self.tableView.dataSource        = self;
    [self.tableView registerClass:[JCTableViewCell class] forCellReuseIdentifier:@"ceId"];
    self.cellHeights = [NSMutableArray array];
    self.layout = [[JCCollectionViewTagFlowLayout alloc] init];
    self.tableView.tableFooterView = [UIView new];
    self.tableView.bounces              = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - <UITableViewDelegate,UITableViewDataSource>

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.tableTags.count == 0) {
        return 0;
    }
    return  self.tableTags.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self.cellHeights[indexPath.row] floatValue]+30;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    JCTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ceId" forIndexPath:indexPath];
    
    if (cell == NULL) {
        cell = [[JCTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"ceId"];
    }
    
    cell.catName.text = self.labelModel[indexPath.row].cat_name;
    tableView.separatorStyle = NO;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    //  标签模块的相关设置
    cell.tagListView.canSelectTags = YES;
    cell.tagListView.tagSelectedTextColor = [UIColor blackColor];
    cell.tagListView.tagCornerRadius = 5.0f;
    [cell.tagListView setCompletionBlockWithSelected:^(NSInteger index) {
        
        //  获取选中标签
        NSString * selectLabel = self.tableTags[indexPath.row][index];
        NSArray *arr = @[selectLabel];
        
        //  添加到已选标签
        NSMutableArray *arr1 = [[NSMutableArray alloc]init];
        [arr1 addObject:selectLabel];
        [self.tagListView.tags addObjectsFromArray:arr1];
        [self.tagListView.collectionView reloadData];
        
        //  删除tableView标签
        [self delete:indexPath.row labelIdex:index arr:arr];
        
        //  通知服务器
       [self addLabelPostActionWithLabelid:self.labelModel[indexPath.row].cat_id labelName:self.labelModel[indexPath.row].cat_name];
    }];
    
    //  对每个cell进行标签赋值
        cell.tags = self.tableTags[indexPath.row];
    
    return cell;
}

-(bool)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

//  已选模块的标签删除动作
- (void)delete{
    [self.tagListView.tags removeObjectsInArray:self.tagListView.selectedTags];
    [self.tagListView.selectedTags removeAllObjects];
    
    [self.tagListView.collectionView reloadData];
}

//  未选模块的标签删除动作
- (void)delete:(NSInteger )celIndex labelIdex:(long )labelIndex arr:(NSArray *)arr{
    
    for (int i = 0; i<self.tableTags.count; i++) {
        [self.tableTags[i] removeObjectsInArray:arr];
    }

    [self.tableView reloadData];
}

@end
